package com.minyifang.wcspf.work.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.md5.SafeUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.work.dialog.presenter.AddToCarPresenter;
import com.minyifang.wcspf.work.dialog.view.AddToCarView;
import com.minyifang.wcspf.work.event.RefreshEvent;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.Global;
import com.minyifang.wcspf.work.ui.home.model.AddToCarBean;
import com.minyifang.wcspf.work.ui.home.model.SpecificationBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 自定义dialog
 * Created by xuyougen on 2018/3/5.
 * <p>
 * 使用方法
 * new CustomDialog.Builder({@link Context})
 * .setTvTitle("标题")
 * .setContent("提示内容")
 * .setListener({@link OnButtonClickListener))
 * .build()
 * .show();
 */

public class AddToCartDialog extends Dialog {
    public AddToCartDialog(@NonNull Context context) {
        super(context);
    }

    public AddToCartDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置dialog 窗体的宽度
        if (getWindow() != null) {
            getWindow().getAttributes().width = WindowManager.LayoutParams.MATCH_PARENT;
            getWindow().getAttributes().gravity = Gravity.BOTTOM;
        }
    }

    public static class Builder implements AddToCarView {
        private Context mContext;
        private String mId;
        private OnButtonClickListener mListener;
        private AddToCarPresenter mPresenter;
        private List<SpecificationBean> mList;
        private AddToCartAdapter mAdapter;

        public Builder(Context context) {
            mContext = context;
        }

        public Builder setGoodsId(String id) {
            mId = id;
            return this;
        }

        public Builder setListener(OnButtonClickListener listener) {
            mListener = listener;
            return this;
        }

        public AddToCartDialog build() {
            mList = new ArrayList<>();
            mPresenter = new AddToCarPresenter();
            mPresenter.attach(this);

            final AddToCartDialog dialog = new AddToCartDialog(mContext, R.style.CustomDialog);

            View layout = View.inflate(mContext, R.layout.layout_add_to_cart_dialog, null);

            TextView confirm = layout.findViewById(R.id.tv_confirm_custom_dialog);

            RecyclerView recyclerView = layout.findViewById(R.id.rv_list);
            mAdapter = new AddToCartAdapter();
            recyclerView.setAdapter(mAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

            confirm.setOnClickListener(v -> {
                dialog.dismiss();
                if (mListener != null) {
                    mListener.onConfirm(dialog);
                }
            });

            //将布局添加到 dialog 中
            dialog.setContentView(layout);
            getSpecificationData();
            return dialog;
        }

        private void getSpecificationData() {
            mPresenter.getSpecification(mId);
        }

        @Override
        public void showLoadingView() {
        }

        @Override
        public void hideLoadingView() {

        }

        @Override
        public void onNetworkError() {

        }

        @Override
        public void showSpecificationRes(HttpRespond<String> respond) {
            if (respond.result == 1) {
                String jsonData;
                if (respond.isaes == 1) {
                    jsonData = SafeUtils.decrypt(respond.data);
                } else
                    jsonData = respond.data;

                LogUtil.e(jsonData);
                List<SpecificationBean> list = new Gson().fromJson(jsonData, new TypeToken<List<SpecificationBean>>() {
                }.getType());
                mList.clear();
                mList.addAll(list);
                mAdapter.notifyDataSetChanged();
            } else if (respond.result == -1) {
                Global.reLogin(mContext);
            } else
                ToastHelper.getInstance(mContext).showWarn(respond.message);
        }

        @Override
        public void showAddToCarRes(HttpRespond<AddToCarBean> respond) {
            if (respond.result == 1) {
                ToastHelper.getInstance(mContext).showSucceed(respond.message);
                sendToUpdateCarNum();
            } else
                ToastHelper.getInstance(mContext).showWarn(respond.message);
        }

        private void sendToUpdateCarNum() {
            EventBus.getDefault().post(new RefreshEvent());
        }

        public class AddToCartAdapter extends RecyclerView.Adapter<AddToCartAdapter.Holder> {

            @NonNull
            @Override
            public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_add_to_cart, parent, false));
            }

            @Override
            public void onBindViewHolder(@NonNull Holder holder, int position) {

                SpecificationBean bean = mList.get(position);
                holder.item_price.setText(String.format("￥%s", bean.getPrice()));
                holder.item_specification.setText(String.format("/(%s%s/%s)", bean.getQuantity(), bean.getComSp(), bean.getSkuSp()));
                holder.item_unit_price.setText(String.format("每%s￥%s元", bean.getComSp(), bean.getUnitPrice()));
                holder.edt_num.setText(bean.getNum());

                holder.edt_num.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s.length() == 0) {
                            holder.edt_num.setText("0");
                            holder.edt_num.setSelection(0,1);
                        }
                    }
                });

                holder.edt_num.setOnFocusChangeListener((v, hasFocus) -> {
                    LogUtil.e(position + "," + bean.getSkuId() + "," + hasFocus);
                    if (!hasFocus) {
                        mPresenter.addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                    }
                });

                holder.itemView.setOnClickListener(v -> holder.itemView.setFocusable(true));

                holder.plus.setOnClickListener((View v) -> {
                    holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) + 1 + "");
                    mPresenter.addToCar(bean.getSkuId(), holder.edt_num.getText().toString());

                });

                holder.reduce.setOnClickListener(v -> {
                    holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) - 1 < 0 ? "0" : Integer.parseInt(holder.edt_num.getText().toString()) - 1 + "");
                    mPresenter.addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                });
            }

            @Override
            public int getItemCount() {
                return mList.size();
            }

            public class Holder extends RecyclerView.ViewHolder {
                @BindView(R.id.item_price)
                TextView item_price;
                @BindView(R.id.item_specification)
                TextView item_specification;
                @BindView(R.id.item_unit_price)
                TextView item_unit_price;
                @BindView(R.id.iv_plus)
                ImageView plus;
                @BindView(R.id.iv_reduce)
                ImageView reduce;
                @BindView(R.id.tv_num)
                EditText edt_num;

                public Holder(View itemView) {
                    super(itemView);
                    ButterKnife.bind(this, itemView);
                }
            }
        }
    }

    /**
     * 监听接口
     */
    public interface OnButtonClickListener {
        void onConfirm(Dialog dialog);
    }

}
